package com.cyzy.controller;

import com.cyzy.dto.Result;
import com.cyzy.pojo.*;
import com.cyzy.service.BannerService;
import com.cyzy.service.CheckService;
import com.cyzy.service.EmailService;
import com.cyzy.service.FileService;
import com.cyzy.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author zxw
 * @create 2025-05-22 下午4:22
 */
@RestController
@RequestMapping("/check")
public class CheckController {

    @Autowired
    private CheckService checkService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmailService emailService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private FileService fileService;

    //审核秒杀
    @GetMapping("/getAllSeckillInfo")
    private Result getAllSeckillInfo(GetSeckillCheck getSeckillCheck){
        //测试获取token中的userId
//        System.out.println(UserContext.getUserId() + "///66666666666666666666666666");
        return checkService.selectAllSeckillInfo(getSeckillCheck);
    }

    @RequestMapping("/updateSeckill")
    private Result updateSeckill(@RequestBody Map<String, String> params) {
        String seckillId = params.get("seckillId");
        String status = params.get("status");
        String rejectReason = params.get("rejectReason");

        // 查询秒杀的课程
        Seckill seckill = checkService.selectCourseId(seckillId);

        // 通过的秒杀信息存入redis
        if ("已通过".equals(status)) {  // 只有在审核通过时才存入Redis
            try {
                //判断秒杀是否已结束
                if (seckill.getEndTime().getTime() < System.currentTimeMillis()) {
                    int result = checkService.updateSeckill(seckillId, "已结束", rejectReason);
                    return Result.error().message("秒杀已结束，不能发布");
                }
                // 计算剩余时间（秒）
                long expireSeconds = (seckill.getEndTime().getTime() - System.currentTimeMillis()) / 1000;

                String redisKey = "seckill" + seckill.getSeckillId();
                // 先删除可能存在的旧数据
                redisTemplate.delete(redisKey);

                // 生成UUID集合存入Redis
                Set<String> codeSet = new HashSet<>();
                for (int i = 0; i < seckill.getTotalLimit(); i++) {
                    codeSet.add(UUID.randomUUID().toString());
                }

                // 批量添加UUID到Redis集合
                if (!codeSet.isEmpty()) {
                    // 1. 存入Redis集合
                    redisTemplate.opsForSet().add(redisKey, codeSet.toArray());
                    redisTemplate.expire(redisKey, expireSeconds, TimeUnit.SECONDS);

                    // 2. 批量存入数据库
                    List<ActivateCode> codeList = new ArrayList<>();
                    for (String code : codeSet) {
                        ActivateCode activateCode = new ActivateCode();
                        activateCode.setActivateCode(code);
                        activateCode.setCourseId(seckill.getCourseId());
                        activateCode.setUserId(Long.parseLong(UserContext.getUserId())); //从token中获取userId
                        activateCode.setCodeStatus("0"); // 0-未使用
                        activateCode.setCreateTime(LocalDateTime.now().toString());
                        codeList.add(activateCode);
                    }

                    // 批量插入数据库
                    checkService.insertSeckill(codeList);

                    // 控制台打印
                    System.out.println("秒杀活动"+seckill.getSeckillId()+"已存入Redis，共生成"
                            +seckill.getTotalLimit()+"个UUID码，过期时间："+expireSeconds+"秒");

                    //获取邮件模版
                    EmailTemplates emailTemplates = checkService.getContent("秒杀审核通知");
                    //替换内容
                    String filledTemplate = emailTemplates.getContent()
                            .replace("{activityTitle}", seckill.getTitle())
                            .replace("{status}", "通过")
                            .replace("{rejectReason}", "");
                    //通知
                    String userEmail = checkService.selectUserEmail(seckill.getSeckillId());

                    emailService.sendSimpleEmail(userEmail, emailTemplates.getSubject(), filledTemplate);
                }

//                //测试取
//                Object code = redisTemplate.opsForSet().pop(redisKey);
//                if (code != null) {
//                    // 抢购成功，使用该code
//                } else {
//                    // 库存已售罄
//                }

            } catch (Exception e) {
                e.printStackTrace();
                return Result.error().message("秒杀信息存入Redis失败，未发布");
            }
        }

        if ("已拒绝".equals(status)) {
            try {
                int result = checkService.updateSeckill(seckillId, "已拒绝", rejectReason);

                //获取邮件模版
                EmailTemplates emailTemplates = checkService.getContent("秒杀审核通知");
                //替换内容
                String filledTemplate = emailTemplates.getContent()
                        .replace("{activityTitle}", seckill.getTitle())
                        .replace("{status}", "拒绝")
                        .replace("{rejectReason}", "拒绝原因：" + rejectReason);
                //通知
                String userEmail = checkService.selectUserEmail(seckill.getSeckillId());
                emailService.sendSimpleEmail(userEmail, emailTemplates.getSubject(), filledTemplate);

                return Result.ok();

            } catch (Exception e) {
                e.printStackTrace();
                return Result.error();
            }
        }
        // 发布完秒杀，更新秒杀信息(如果存入redis失败则不更新)
        int result = checkService.updateSeckill(seckillId, "已发布", rejectReason);
        return Result.ok();
    }

    //审核活动
    @GetMapping("/getAllActivityInfo")
    private Result getAllActivityInfo(GetActivityCheck getActivityCheck){
        return checkService.selectAllActivityInfo(getActivityCheck);
    }

    @RequestMapping("/updateActivity")
    private Result updateActivity(@RequestBody Map<String, String> params) {
        String activityId = params.get("activityId");
        String activityStatus = params.get("activityStatus");
        String rejectReason = params.get("rejectReason");

        Activity activity = checkService.selectActivity(activityId);

        //获取邮件模版
        EmailTemplates emailTemplates = checkService.getContent("活动审核通知");

        // 通过的活动信息
        if ("已通过".equals(activityStatus)) {
            try {
                int result = checkService.updateActivity(activityId, "已通过", rejectReason);

                //替换内容
                String filledTemplate = emailTemplates.getContent()
                        .replace("{activityTitle}", activity.getTitle())
                        .replace("{status}", "通过")
                        .replace("{rejectReason}", "");
                //通知
                String userEmail = checkService.selectActivityUserEmail(activity.getActivityId());
                emailService.sendSimpleEmail(userEmail, emailTemplates.getSubject(), filledTemplate);

                return Result.ok();

            } catch (Exception e) {
                e.printStackTrace();
                return Result.error();
            }
        }

        if ("已拒绝".equals(activityStatus)) {
            try {
                int result = checkService.updateActivity(activityId, "已拒绝", rejectReason);

                //替换内容
                String filledTemplate = emailTemplates.getContent()
                        .replace("{activityTitle}", activity.getTitle())
                        .replace("{status}", "拒绝")
                        .replace("{rejectReason}", "拒绝原因：" + rejectReason);
                //通知
                String userEmail = checkService.selectActivityUserEmail(activity.getActivityId());
                emailService.sendSimpleEmail(userEmail, emailTemplates.getSubject(), filledTemplate);

                return Result.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error();
            }
        }
        return Result.ok();
    }


    //审核广告
    @GetMapping("/getAllAdvertInfo")
    public Result getAllAdvertInfo(GetAdvertCheck getAdvertCheck) {
        // 参数校验
        if (getAdvertCheck.getCurrentPage() == null || getAdvertCheck.getCurrentPage() <= 0) {
            getAdvertCheck.setCurrentPage(1L);
        }
        if (getAdvertCheck.getPageSize() == null || getAdvertCheck.getPageSize() <= 0) {
            getAdvertCheck.setPageSize(10L);
        }
        return checkService.selectAllAdvertInfo(getAdvertCheck);
    }

    @PostMapping("/updateAdvert")
    public Result updateAdvert(@RequestBody Map<String, String> params) {
        // 参数校验
        if (params == null || params.isEmpty()) {
            return Result.error().message("参数不能为空");
        }

        String advertId = params.get("advertId");
        String status = params.get("status");
        String rejectReason = params.get("rejectReason");

        if (advertId == null || advertId.isEmpty()) {
            return Result.error().message("广告ID不能为空");
        }
        if (status == null || status.isEmpty()) {
            return Result.error().message("审核状态不能为空");
        }

        // 获取广告信息
        Advert advert = checkService.selectAdvertById(advertId);
        if (advert == null) {
            return Result.error().message("未找到对应的广告信息");
        }

        // 获取邮件模板
        EmailTemplates emailTemplates = checkService.getContent("广告审核通知");
        if (emailTemplates == null) {
            return Result.error().message("未找到邮件模板");
        }

        try {
            // 处理审核通过
            if ("已通过".equals(status)) {
                int result = checkService.updateAdvert(advertId, "已通过", "");
                if (result <= 0) {
                    return Result.error().message("更新广告状态失败");
                }
                FileInfo fileInfo = fileService.getFileInfo(Long.valueOf(advert.getFileId()));

                Banner banner = new Banner();
                banner.setTitle(advert.getAdvertTitle());
                banner.setImageUrl(fileInfo.getUrl());
                banner.setLinkUrl(advert.getLinkUrl());
                banner.setBannerSort(1L);
                banner.setBannerType(advert.getAdvertType());
                banner.setCampusId(advert.getCampusId());
                banner.setCourseId(advert.getCourseId());
                banner.setIsVisible(1);
                banner.setStartTime(advert.getStartTime());
                banner.setEndTime(advert.getEndTime());

                bannerService.addBanner(banner);

                // 替换邮件模板内容
                String filledTemplate = emailTemplates.getContent()
                        .replace("{advertTitle}", advert.getAdvertTitle())
                        .replace("{status}", "通过")
                        .replace("{rejectReason}", "");

                // 发送通知邮件
                String userEmail = checkService.selectAdvertUserEmail(Long.parseLong(advertId));
                if (userEmail != null && !userEmail.isEmpty()) {
                    emailService.sendSimpleEmail(userEmail, emailTemplates.getSubject(), filledTemplate);
                }

                return Result.ok().message("广告审核通过成功");
            }

            // 处理审核拒绝
            if ("已拒绝".equals(status)) {
                if (rejectReason == null || rejectReason.isEmpty()) {
                    return Result.error().message("拒绝原因不能为空");
                }

                int result = checkService.updateAdvert(advertId, "已拒绝", rejectReason);
                if (result <= 0) {
                    return Result.error().message("更新广告状态失败");
                }

                // 替换邮件模板内容
                String filledTemplate = emailTemplates.getContent()
                        .replace("{advertTitle}", advert.getAdvertTitle())
                        .replace("{status}", "拒绝")
                        .replace("{rejectReason}", "拒绝原因：" + rejectReason);

                // 发送通知邮件
                String userEmail = checkService.selectAdvertUserEmail(Long.parseLong(advertId));
                if (userEmail != null && !userEmail.isEmpty()) {
                    emailService.sendSimpleEmail(userEmail, emailTemplates.getSubject(), filledTemplate);
                }

                return Result.ok().message("广告审核拒绝成功");
            }

            return Result.error().message("无效的审核状态");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("广告审核处理异常: " + e.getMessage());
        }
    }

}
